package com.example.dangdangbackend.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import cn.hutool.captcha.generator.RandomGenerator;
import com.example.dangdangbackend.DTO.LoginDTO;
import com.example.dangdangbackend.DTO.RegisterDTO;
import com.example.dangdangbackend.VO.UserLoginVO;
import com.example.dangdangbackend.common.BaseContext;
import com.example.dangdangbackend.common.CustomException;
import com.example.dangdangbackend.entity.Result;
import com.example.dangdangbackend.entity.User;
import com.example.dangdangbackend.service.UserService;
import com.example.dangdangbackend.utils.JwtUtil;
import jakarta.mail.MessagingException;
import jakarta.servlet.http.HttpServletResponse;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    private UserService userService;


    private LineCaptcha lineCaptcha;

    private static String emailCode;
    /**
     * 进行用户登录操作 DTO为前后端的数据传输流
     *
     * @param loginDTO
     * @return
     */
    @PostMapping("/login")
    public Result<UserLoginVO> Login(LoginDTO loginDTO) {
        log.info("email:{},password:{}", loginDTO.getEmail(), loginDTO.getPassword());
        User user = userService.UserLogin(loginDTO);

        //登录成功，生成jwt令牌
        BaseContext.setCurrentId(user.getUserId());
        Map<String, Object> claims = new HashMap<>();
        claims.put("id", user.getUserId());
        claims.put("email", user.getEmail());
        claims.put("nickName", user.getNickName());
        String token = JwtUtil.genToken(claims);

        //后端返回结果进行封装
        UserLoginVO userLoginVO = UserLoginVO.builder()
                .id(user.getUserId())
                .nickName(user.getNickName())
                .email(user.getEmail())
                .token(token)
                .build();

        return Result.success(userLoginVO);
    }

    /**
     * 注册操作
     * @param registerDTO
     * @return
     */
    @PostMapping("/register")
    public Result<String> register(RegisterDTO registerDTO) {
        log.info("注册人信息为{}",registerDTO.toString());
        boolean register = userService.Register(registerDTO, emailCode);
        if(register){
            emailCode = null;
            return Result.success("注册成功");
        }

        return Result.error("注册失败");
    }

    @PostMapping("/ifExist")
    public Result<Boolean> ifExist(String email){
        log.info("判断用户的email:{}",email);

        return Result.success(userService.ifExist(email));
    }

    /**
     * 向用户的邮箱发送验证码
     * @param email
     * @return
     * @throws MessagingException
     */
    @PostMapping("sendEmail")
    public Result<String> sendEmail(String email) throws MessagingException {
        log.info("发送的邮箱为：{}",email);
        try{
           emailCode = userService.sendEmail(email);
        }catch (MessagingException e){
            throw new CustomException("验证码发送失败");
        }


        return Result.success("验证码发送成功");
    }

    /**
     * 判断填写验证码是否相同
     * @param Code
     * @return
     */
    @PostMapping("/codeRight")
    public Result codeRight(String Code){
        log.info("Code为{}",Code);
        if(Code==null){
            return Result.error("验证失败");
        }

        if(Code.equals(lineCaptcha.getCode())){
            return Result.success(true);
        }else {
            return Result.success(false);
        }
    }

    /**
     * 发送验证码图片
     * @param response
     */
    @RequestMapping("/getCode")
    public void getCode(HttpServletResponse response) {
        // 随机生成 4 位验证码
        RandomGenerator randomGenerator = new RandomGenerator("0123456789", 4);
        // 定义图片的显示大小
        lineCaptcha = CaptchaUtil.createLineCaptcha(80, 40);
        response.setContentType("image/jpeg");
        response.setHeader("Pragma", "No-cache");
        try {
            // 调用父类的 setGenerator() 方法，设置验证码的类型
            lineCaptcha.setGenerator(randomGenerator);
            // 输出到页面
            lineCaptcha.write(response.getOutputStream());
            // 打印日志
            log.info("生成的验证码:{}", lineCaptcha.getCode());
            // 关闭流
            response.getOutputStream().close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
